import { Injectable } from '@nestjs/common';
// import { LoginParamsDto } from './dto';
import { JwtService } from '@nestjs/jwt';
import { InjectModel } from '@nestjs/sequelize';
import { User } from '@/models/user.model';
import { LoginParamsDto } from './dto';
import { type WhereOptions } from 'sequelize/types';
import { responseMessage } from '@/utils';
@Injectable()
export class AuthService {
  constructor(
    @InjectModel(User)
    private readonly userModel: typeof User,
    private readonly jwtService: JwtService,
  ) {}

  async login(loginParams: LoginParamsDto) {
    const authResult = await this.validateUser(loginParams);
    if (authResult.code === 200) {
      const token: any = await this.jwtService.signAsync({
        userId: authResult.data.id,
      });
      return responseMessage(
        {
          access_token: token,
        },
        '登录成功!',
        200,
      );
    } else {
      return authResult;
    }
  }

  async validateUser(loginParams: LoginParamsDto): Promise<any> {
    const { account, password } = loginParams;
    const where: WhereOptions = { account };
    const userInfo = await this.userModel.findOne({ where });
    if (!userInfo) {
      return responseMessage(null, '用户名或密码不正确!', -1);
    } else if (userInfo.password !== password) {
      return responseMessage({}, '用户名或密码不正确!', -1);
    } else {
    }
    return responseMessage(userInfo, '登录成功!');
  }

  async register(loginParams: LoginParamsDto) {
    const { account } = loginParams;
    const where: WhereOptions = { account };
    const userInfo = await this.userModel.findOne({ where });
    if (userInfo) {
      return responseMessage(null, '用户已存在!', -1);
    }
    try {
      const result = await this.userModel.create({ ...loginParams });

      const token: any = await this.jwtService.signAsync({ userId: result.id });
      return responseMessage(
        {
          access_token: token,
        },
        '注册并登录成功!',
        200,
      );
    } catch (error) {
      return responseMessage(null, '创建用户失败!', -1);
    }
  }
}
